package com.zyl.pc;

/**
 * @author zhaoyl
 * @date 2024/5/15 14:59
 * @description
 * 线程件的通信问题：生产者和消费者；等待唤醒，通知唤醒
 * 线程交替执行A B 操作同一个变量
 * 线程通知 synchronized
 */
public class WaitNotify {
    public static void main(String[] args) {
        Data data = new Data();
        //开启线程
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程A加法").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    data.decrment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程B减法").start();
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    data.decrment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程C减法").start();
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程D加法").start();
    }
}

//等待，业务，通知
class  Data { //资源类
    private int number = 0;
    //+1 同步锁
    public  synchronized void increment() throws InterruptedException{
        //注意这里如果使用一次判断if 超过2个线程则会产生虚假唤醒，导致混乱 wait()必须在循环中
        while (number!=0){
            //等待
            this.wait();
        }
        number++;
        System.out.println("当前"+Thread.currentThread().getName()+"=>"+number);
        //通知其他线程，我+1完成
        this.notifyAll();//唤醒
    }
    //-1 同步锁
    public  synchronized void decrment() throws InterruptedException{
        while (number==0){
            //等待
            this.wait();
        }
        number--;
        System.out.println("当前"+Thread.currentThread().getName()+"=>"+number);
        //通知其他线程，我-1完成
        this.notifyAll();
    }
}
